subjectID = 'K091412S';
ROI_t_thresh = 5;

FOBSdir = ['/Volumes/cluster/jet/mattar/AdaptID/Analyses/' subjectID '/FOBSLoc.feat/stats'];
FOBSfileZIP = [FOBSdir '/' 'tstat1.nii.gz'];

workingDir = ['/Volumes/cluster/jet/mattar/AdaptID/Analyses/' subjectID '/Face1.feat'];
filteredDataZIP = [workingDir '/' 'filtered_func_data.nii.gz'];





% Gunzip FOBS data
FOBSfile_filename = gunzip(FOBSfileZIP, '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Analysis');
FOBSfile_filename = FOBSfile_filename{1};

% Load FOBS data .nii file in MATLAB
%FOBSroiStruct = load_nii(FOBSfile_filename);
FOBSroiStruct = load_untouch_nii(FOBSfile_filename);
FOBSroi = FOBSroiStruct.img;
FOBSroi_mask = FOBSroi > ROI_t_thresh;

% Delete FOBS .nii file
eval(['delete ' FOBSfile_filename]);





% Gunzip filtered data
filteredData_filename = gunzip(filteredDataZIP, '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/AdaptID/Analysis');
filteredData_filename = filteredData_filename{1};

% Load filteredData .nii file in MATLAB
%filteredDataStruct = load_nii(filteredData_filename);
filteredDataStruct = load_untouch_nii(filteredData_filename);
filteredData = filteredDataStruct.img;

% Delete filteredData .nii file
eval(['delete ' filteredData_filename]);









numTRs = size(filteredData,4);
ffaSignal = zeros(numTRs,1);
ffa_simBrain = zeros(1,1,1,numTRs);

for t = 1:numTRs
    maskedData = filteredData(:,:,:,t) .* FOBSroi_mask;
    ffaSignal(t,1) = mean(maskedData(:));
    ffa_simBrain(1,1,1,t) = ffaSignal(t,1);
end


% Create a .nii file with the ffa signal
ffaSignalStruct = filteredDataStruct;
ffaSignalStruct.img = ffa_simBrain;
% Change the header file to avoid conflicts
ffaSignalStruct.hdr.dime.dim(2:4) = 1;
ffaSignalStruct.fileprefix = [workingDir '/ffaSignal'];

%save_nii(ffaSignalStruct,[workingDir '/ffaSignal.nii']);
save_untouch_nii(ffaSignalStruct,[workingDir '/ffaSignal.nii']);